#! /bin/sh
# postinst maintainer script for zoneminder-core package

set -e

# Source the debconf stuff
. /usr/share/debconf/confmodule

# Source the config file
CONFIGFILE=/etc/zm/zm.conf
. $CONFIGFILE

# Do this when the package is installed, upgraded or reconfigured
if [ "$1" = "configure" ] || [ "$1" = "reconfigure" ]; then

    # Retrieve data from dbconfig (inputs from user)
    . /etc/dbconfig-common/zoneminder.conf

    # ZoneMinder config file handling
    # Inspired by: http://manpages.debian.org/cgi-bin/man.cgi?query=debconf-devel&sektion=7

    # Backup the config file
    cp -a -f $CONFIGFILE ${CONFIGFILE}.postinst.bak

    # Redeclare variables if missing in config file
    test -z $dbc_dbserver || grep -Eq "^ *ZM_DB_HOST=" $CONFIGFILE \
      || echo "ZM_DB_HOST=" >> ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbname || grep -Eq "^ *ZM_DB_NAME=" $CONFIGFILE \
      || echo "ZM_DB_NAME=" >> ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbuser || grep -Eq "^ *ZM_DB_USER=" $CONFIGFILE \
      || echo "ZM_DB_USER=" >> ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbpass || grep -Eq "^ *ZM_DB_PASS=" $CONFIGFILE \
      || echo "ZM_DB_PASS=" >> ${CONFIGFILE}.postinst.bak

    # Prevent ZM_DB_HOST to be empty if user selected the 'unix socket' method
    if test -z $dbc_dbserver; then
	dbc_dbserver_override="localhost"
    else
        dbc_dbserver_override=$dbc_dbserver
    fi

    # Update variables in config file
    sed -i "s/^ *ZM_DB_HOST=.*/ZM_DB_HOST=$dbc_dbserver_override/" \
      ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbname || sed -i "s/^ *ZM_DB_NAME=.*/ZM_DB_NAME=$dbc_dbname/" \
      ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbuser || sed -i "s/^ *ZM_DB_USER=.*/ZM_DB_USER=$dbc_dbuser/" \
      ${CONFIGFILE}.postinst.bak
    test -z $dbc_dbpass || sed -i "s/^ *ZM_DB_PASS=.*/ZM_DB_PASS=$dbc_dbpass/" \
      ${CONFIGFILE}.postinst.bak

    # Clean-up backup file
    mv -f ${CONFIGFILE}.postinst.bak $CONFIGFILE


    # Set some file permissions
    chown $ZM_WEB_USER:$ZM_WEB_GROUP /var/log/zm
    if [ -z "$2" ]; then
        chown $ZM_WEB_USER:$ZM_WEB_GROUP -R /var/cache/zoneminder
    fi
    # As requested by the Debian Webapps Policy Manual §3.2.1
    chown root:${ZM_WEB_GROUP} $CONFIGFILE
    chmod 640 $CONFIGFILE
fi

# Do this every time the package is installed or upgraded
# Test for database presence to avoid failure of zmupdate.pl
if [ "$dbc_install" = "true" ] && [ "$1" = "configure" ]; then

    # Ensure zoneminder is stopped
    deb-systemd-invoke stop zoneminder.service || exit $?

    # Run the ZoneMinder update tool
    zmupdate.pl --nointeractive

fi

#DEBHELPER#

exit 0
